<?php
	include "../public/commom/config.php";//引入配置连接数据库文件
	include "../public/commom/commom.php";//引入配置图片文件
	include "../public/commom/timename.php";//引入配置时间文件
	
	if($_POST) {
		$user_id = $_POST["user_id"];
		
		$sql = "SELECT * FROM(
(SELECT privateletter.*, privateletter.tuser_id tuid, user.headportrait, user.username FROM privateletter LEFT JOIN user ON (privateletter.tuser_id = user.id) WHERE privateletter.user_id = '$user_id')
UNION 
(SELECT privateletter.*, privateletter.user_id tuid, user.headportrait, user.username FROM privateletter LEFT JOIN user ON (privateletter.user_id = user.id) WHERE privateletter.tuser_id = '$user_id')) AS c
GROUP BY c.tuid ORDER BY time DESC";//sql语句 - 查找所有给自己私信的用户
		
		$result = mysqli_query($conn, $sql);//result - 执行sql语句
		
		$headnum = mysqli_num_rows($result);//用户数量
		
		if($_SESSION["cheadnum"] < $headnum){
			$poor = $headnum - $_SESSION["cheadnum"];
			
			$_SESSION["cheadnum"] = $headnum;
			
			if($poor > 0) {
				$headlist = array();
				
				$i = 0;
				
				while($row = mysqli_fetch_array($result)) {
					$sql1 = "SELECT privateletter.* FROM privateletter LEFT JOIN user ON (privateletter.user_id = user.id) WHERE privateletter.user_id = '$user_id' AND privateletter.tuser_id = " . $row["tuid"] . " AND privateletter.status = '0'";//sql语句 - 查找该用户未读私信数量
							
					$result1 = mysqli_query($conn, $sql1);//result - 执行sql语句
					
					if(mysqli_num_rows($result1)) {
						$unread = mysqli_num_rows($result1);//该用户未读私信数量
					}else {
						$unread = "";//该用户未读私信数量
					}
					
					$headlist[$i] = $row;
					$headlist[$i]["unread"] = $unread;
					$i++;
				}
				
				$head = array("headlist" => $headlist, "poor" => "$poor");//数组
				
				echo json_encode($head);//以json格式输出
				
				mysqli_free_result($result);//释放内存
				
				mysqli_close($conn);//关闭数据库连接
			}
		}
	}
?>